#!/usr/bin/env python3
"""测试指标查询"""
import os
import sys
from pathlib import Path
import json
from datetime import datetime, timezone, timedelta

from python.collector.skywalking_collector import SkyWalkingCollector

sys.path.insert(0, str(Path(__file__).parent))

from dotenv import load_dotenv

# 加载配置
env_path = Path(__file__).parent / "config.env"
if env_path.exists():
    load_dotenv(env_path)

SKYWALKING_URL = os.getenv('SKYWALKING_URL', 'http://10.10.50.46:12800/graphql')

print("=" * 80)
print("测试 SkyWalking 指标查询")
print("=" * 80)
print()

collector = SkyWalkingCollector(SKYWALKING_URL)

# 获取服务列表
print("1. 获取服务列表...")
services = collector.get_all_services(30)
if services:
    test_service = services[0]
    print(f"测试服务: {test_service['name']} (ID: {test_service['id']})")
    print()
    
    # 测试查询指标
    print("2. 查询服务指标 (service_resp_time)...")
    metric_data = collector.get_service_metric('service_resp_time', test_service['name'], 30)
    
    print("\n原始指标数据：")
    print(json.dumps(metric_data, indent=2, ensure_ascii=False))
    
    if metric_data:
        print("\n3. 尝试提取时间序列...")
        try:
            time_series = collector.extract_metric_time_series(metric_data)
            print(f"提取到 {len(time_series)} 个数据点")
            if time_series:
                print("\n前 3 个数据点:")
                for ts, val in time_series[:3]:
                    print(f"  时间: {ts}, 值: {val}")
            else:
                print("⚠️  提取结果为空！")
        except Exception as e:
            print(f"❌ 提取失败: {e}")
            import traceback
            traceback.print_exc()
    else:
        print("⚠️  指标数据为空！")
else:
    print("⚠️  没有服务数据")

print()
print("=" * 80)

